<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item label="企业名称：">
          <el-select
            v-model="queryParams.wspolluteid"
            placeholder="请选择企业名称"
            style="width: 180px"
          >
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.polluteid"
              :label="item.pollutename"
              :value="item.polluteid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入河排污口名称：">
          <el-select
            v-model="queryParams.rhoutfallid"
            placeholder="请选择入河排污口名称"
            style="width: 180px"
          >
            <el-option
              v-for="item in portOptions"
              :key="item.id"
              :label="item.lakename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
            style="padding: 10px"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-refresh"
            @click="handleReset"
            style="padding: 10px"
            >重置</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            style="padding: 10px"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="pageContent">
      <el-table :data="tableList.rows" stripe :height="tableHeight" border>
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          prop="wspollutename"
          label="企业名称"
        ></el-table-column>
        <el-table-column
          prop="rhoutfallname"
          label="入河排污口名称"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>
    <!-- 添加或修改排污口信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      @opened="resetFormAfterOpen"
    >
      <!-- 确保ref="form"与代码中调用的一致 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="企业名称" prop="wspolluteid">
          <el-select
            v-model="form.wspolluteid"
            placeholder="请选择企业名称"
            style="width: 100%"
          >
            <el-option
              v-for="item in enterpriseOptions"
              :key="item.polluteid"
              :label="item.pollutename"
              :value="item.polluteid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入河排污口名称" prop="rhoutfallid">
          <el-select
            v-model="form.rhoutfallid"
            placeholder="请选择入河排污口名称"
            style="width: 100%"
          >
            <el-option
              v-for="item in portOptions"
              :key="item.id"
              :label="item.lakename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAssociationList,
  editAssociation,
  deleteAssociation,
  addAssociation,
  getAssociationDetail,
  getEnterpriseOptions,
  getDischargeOptions,
} from "@/api/traceability";
export default {
  name: "PollutionPortManage",
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wspolluteid: "",
        rhoutfallid: "",
      },
      tableList: {
        total: 3,
        rows: [],
      },

      open: false, // 弹窗默认关闭
      title: "",
      form: {
        // 表单初始值
        wspolluteid: "",
        rhoutfallid: "",
      },
      rules: {
        wspolluteid: [
          { required: true, message: "请选择企业名称", trigger: "change" },
        ],
        rhoutfallid: [
          {
            required: true,
            message: "请选择入河排污口名称",
            trigger: "change",
          },
        ],
      },
      enterpriseOptions: [],
      portOptions: [],
      // 选中数组
      ids: [],
    };
  },
  created() {
    this.getEnterpriseSelect();
    this.getDischargeSelect();
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取企业下拉列表
    getEnterpriseSelect() {
      getEnterpriseOptions().then((response) => {
        console.log("企业下拉列表数据：", response);
        this.enterpriseOptions = response.data;
      });
    },
    // 获取排污口下拉列表
    getDischargeSelect() {
      getDischargeOptions().then((response) => {
        console.log("排污口下拉列表数据：", response);
        this.portOptions = response.data;
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleReset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        wspolluteid: "",
        rhoutfallid: "",
      };
      // 重置查询表单（需先判断ref是否存在）
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.getList();
    },
    handleAdd() {
      this.title = "添加排污口信息";
      this.open = true; // 先打开弹窗，表单渲染后触发@opened事件
    },
    handleEdit(row) {
      this.title = "修改排污口信息";
      console.log("修改数据：", row);
      this.form = { ...row }; // 赋值修改数据
      this.open = true; // 打开弹窗，渲染后重置（避免残留校验状态）
    },
    handleDelete(row) {
      let id;
      if (row) {
        id = row.id;
      } else {
        id = this.ids.join(",");
      }
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return deleteAssociation(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    cancel() {
      this.open = false;
      // 关闭弹窗时重置表单（需判断ref是否存在）
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    // 弹窗打开后执行（表单已渲染，可安全调用resetFields）
    resetFormAfterOpen() {
      if (this.$refs.form) {
        this.$refs.form.resetFields();
        // 若为修改，弹窗打开后重新赋值（避免resetFields清空数据）
        if (this.title === "修改排污口信息") {
          this.$nextTick(() => {
            this.form = { ...this.form }; // 重新赋值，触发表单更新
          });
        }
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            editAssociation(this.form).then((res) => {
              this.open = false;
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          } else {
            addAssociation(this.form).then((res) => {
              this.open = false;
              this.$modal.msgSuccess("新增成功");
              this.getList();
            });
          }
        }
      });
    },
    getList() {
      // 实际项目中替换为接口请求
      console.log("获取表格数据，参数：", this.queryParams);
      getAssociationList(this.queryParams).then((res) => {
        console.log("表格数据：", res);
        this.tableList.total = res.total;
        this.tableList.rows = res.rows;
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .el-form-item__content {
      min-width: 200px;
    }
  }

  .pageContent {
    .el-table {
      width: 100%;
    }
  }
}
</style>
